# -*- coding: utf-8 -*-
# vim: set et sw=4 sts=4 fileencoding=utf-8:
#
# PyPRTG - A Python helper library for PRTG
#
# Copyright (c) 2019 Paessler AG
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""
SSL Helper functions.
"""

import ssl

__all__ = ["create_ssl_context"]


def create_ssl_context(allow_self_signed_cert, check_hostname):
    """
    Creates a TLSv1.2 SSL context.

    @param allow_self_signed_cert: Allow self-signed certificates.
    @type allow_self_signed_cert: bool
    @param check_hostname: Check whether the certificates' hostname
                           matches with the peer's hostname.
    @type check_hostname: bool

    @return: A TLSv1.2 SSL context object.
    @rtype: SSLContext
    """
    ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
    ssl_context.check_hostname = check_hostname
    # ssl_context.verify_mode = \
    #     allow_self_signed_cert \
    #     and ssl.CERT_NONE \
    #     or ssl.CERT_REQUIRED
    if allow_self_signed_cert and not check_hostname:
        ssl_context.verify_mode = ssl.CERT_NONE

    # Forbid anything below TLSv1.2
    ssl_context.options |= (
        ssl.PROTOCOL_TLS
        | ssl.OP_NO_SSLv2
        | ssl.OP_NO_SSLv3
        | ssl.OP_NO_TLSv1
        | ssl.OP_NO_TLSv1_1
    )

    return ssl_context
